package com.situ.user.controller;

import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import com.situ.user.bean.User;
import com.situ.user.service.UserService;

@Controller
@RequestMapping("/user")
public class UserController {

	@Autowired
	private UserService userService;

	@GetMapping("/reg")
	public String reg() {
		return "user/reg";
	}

	// 用户注册
	@PostMapping("/reg")
	public String reg(User user, String repassword, Model model) {
		int result = userService.reg(user, repassword);
		if (result > 0) {
			return "redirect:login";
		} else {
			// 传递错误信息
			String error = "未知错误，请联系管理员！！！";
			if (result == -1) {
				error = "账号格式不正确";
			} else if (result == -2) {
				error = "密码格式不正确";
			} else if (result == -3) {
				error = "两次密码不一致";
			} else if (result == -4) {
				error = "账号不可用";
			}
			model.addAttribute("error", error);
			// 跳转页面
			return "user/reg";
		}

	}

	@GetMapping("/login")
	public String login() {
		return "user/login";
	}

	@PostMapping("/login")
	public String login(User user, Model model, HttpSession session) {
		try {
			user = userService.login(user);
			// 保存信息到session
			session.setAttribute("user", user);
			return "redirect:/";
		} catch (Exception e) {
			e.printStackTrace();
			model.addAttribute("error", e.getMessage());
			return "user/login";
		}
	}

	// 退出登录
	@GetMapping("/logout")
	public String logout(HttpSession session) {
		session.invalidate();
		return "redirect:/";
	}
}
